﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bosphorus.Migrator.Core.MigrationCommand;

namespace Bosphorus.Migrator.Core.Command.Grouper
{
    public static class CommandGrouper
    {
        public static IDictionary<string, IList<ICommand>> ByModel(IList<ICommand> commandList)
        {
            IDictionary<string, IList<ICommand>> commandListDictionary = new Dictionary<string, IList<ICommand>>();
            foreach (ICommand command in commandList)
            {
                string modelName = GetModelName(command);
                IList<ICommand> modelCommandList = GetCommandList(commandListDictionary, modelName);
                modelCommandList.Add(command);
            }

            return commandListDictionary;
        }

        public static IDictionary<string, IList<ICommand>> ByCommandType(IList<ICommand> commandList)
        {
            IDictionary<string, IList<ICommand>> commandListDictionary = new Dictionary<string, IList<ICommand>>();
            foreach (ICommand command in commandList)
            {
                string modelName = GetCommandType(command);
                IList<ICommand> modelCommandList = GetCommandList(commandListDictionary, modelName);
                modelCommandList.Add(command);
            }

            return commandListDictionary;
        }

        private static IList<ICommand> GetCommandList(IDictionary<string, IList<ICommand>> commandListDictionary, string modelName)
        {
            if (commandListDictionary.ContainsKey(modelName))
                return commandListDictionary[modelName];

            IList<ICommand> commandList = new List<ICommand>();
            commandListDictionary.Add(modelName, commandList);
            return commandList;
        }

        private static string GetCommandType(ICommand command)
        {
            return command.Name;
        }

        private static string GetModelName(ICommand command)
        {
            Type commandModelType = command.Model.GetType();
            string commandModelTypeName = commandModelType.Name;
            return commandModelTypeName;
        }
    }
}
